/*
 * NetUtils.cpp
 *
 *  Created on: 23.05.2011
 *      Author: mifodix
 */

#include "NetUtils.hpp"

NetUtils::NetUtils()
{
}

uint32_t NetUtils::HostOrd2NetOrd(uint32_t hostOrder)
{
	return htonl(hostOrder);
}

uint16_t NetUtils::HostOrd2NetOrd(uint16_t hostOrder)
{
	return htons(hostOrder);
}

uint32_t NetUtils::NetOrd2HostOrd(uint32_t networkOrder)
{
	return ntohl(networkOrder);
}

uint16_t NetUtils::NetOrd2HostOrd(uint16_t networkOrder)
{
	return ntohs(networkOrder);
}

size_t NetUtils::List2Chars(std::list<uint32_t> l, char *&array, bool toNetOrder)
{
	size_t size=l.size()*sizeof(uint32_t);
	array=new char[size];
	char *cur=array;
	uint32_t temp;
	for (std::list<uint32_t>::iterator it=l.begin(); it!=l.end(); ++it)
	{
		temp=*it;
		if (toNetOrder)
		{
			temp=NetUtils::HostOrd2NetOrd(temp);
		}
		memmove(cur, &temp, sizeof(temp));
		cur+=sizeof(temp);
	}
	return size;
}

bool NetUtils::CheckIPSubnet(uint32_t ip, uint32_t subnet, uint32_t mask)
{
	if ((ip&mask)==subnet) return true;
	return false;
}

char *NetUtils::IP2String(uint32_t networkOrderedIP)
{
	struct in_addr addr;
	addr.s_addr=networkOrderedIP;
	char *res=new char[32];
	strcpy(res, inet_ntoa(addr));
	return res;
}

NetUtils::~NetUtils()
{
}

uint32_t NetUtils::String2IP(const char *strIP)
{
	uint32_t addr;
	if (inet_pton(AF_INET, strIP, &addr)>0)
	{
		return ntohl(addr);
	}
	return 0;
}
